package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.beans.Transient;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public Map<String,List<Catelog2Vo>> getCatalogJson(){
        //给缓存中放入json字符串，拿出的json字符串，还用逆转为能用的对象类型【序列化与反序列化】

        /**
         * 1,空结果缓存，解决缓存穿透
         * 2，设置过期时间（加随机值），解决缓存雪崩
         * 3，加锁，解决缓存击穿
         */
        //1，加入缓存逻辑，缓存中存的数据是json字符串
        //json跨语言，跨平台兼容
        String catelogJSON = redisTemplate.opsForValue().get("catelogJSON");
        if (StringUtils.isEmpty(catelogJSON)){
            //2,缓存中没有，查询数据库
            Map<String,List<Catelog2Vo>> catalogJsonFromDB = getCatalogJsonFromDB();
            //3，查到的数据再放入缓存，将对象转为json放在缓存中
            String s = JSON.toJSONString(catalogJsonFromDB);
            redisTemplate.opsForValue().set("catelogJSON",s);
            return catalogJsonFromDB;
        }
        //转为我们指定的对象
        Map<String,List<Catelog2Vo>> result = JSON.parseObject(catelogJSON,new TypeReference<Map<String,List<Catelog2Vo>>>(){});

        return result;
    }

    //从数据库查询并封装分类数据
    public Map<String,List<Catelog2Vo>> getCatalogJsonFromDB(){

        synchronized (this){
            String catelogJSON = redisTemplate.opsForValue().get("catelogJSON");
            if (StringUtils.isEmpty(catelogJSON)){
                Map<String,List<Catelog2Vo>> result = JSON.parseObject(catelogJSON,new TypeReference<Map<String,List<Catelog2Vo>>>(){});

                return result;
            }
            //将数据库的多次查询变为一次
            List<CategoryEntity> select = baseMapper.selectList(null);
        }
        return null;}

    @Override
    public List<CategoryEntity> listWithTree() {

        //查询所有数据
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        //查询分类
        //stream().filter()一般适用于list集合,主要作用就是模拟sql查询，从集合中查询想要的数据。filter里面的参数是指集合里面的每一项
        //parentCid父分类id
        List<CategoryEntity> levelEntitles = categoryEntities.stream().filter(categoryEntity -> categoryEntity.getParentCid()==0)
                .map((menu) -> {menu.setChildren(getChildren(menu,categoryEntities));return menu;
                //排序
                }).sorted((menu1,menu2) -> {
                    return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());})
                .collect(Collectors.toList());

        return levelEntitles;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1 检查当前的菜单是否被别的地方所引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId,paths);

        Collections.reverse(parentPath);

        return  parentPath.toArray(new Long[parentPath.size()]);
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        //收集当前节点
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }

    /**
     * 级联更新所有关联的数据
     * @CacheEvict失效模式
     * @param category
     */
    @CacheEvict(value = {"category"},key = "#root.methodName")
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {

        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            //parentCid父分类id,catId分类id
            return categoryEntity.getParentCid() == root.getCatId();
        }).map((categoryEntity -> {
            //找到子菜单
                    categoryEntity.setChildren(getChildren(categoryEntity, all));
                    return categoryEntity;
                }
                //菜单的排序
                )).sorted((menu1, menu2) -> {
                    return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());})
                .collect(Collectors.toList());

        return children;
    }

}